from django.views import View

from User.models import UserCoupon
from Venue.models import Coupon
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequiredUser


class CouponView(LoginRequiredUser, View):
    """ 优惠券信息 """

    def get(self, request):
        """ 查询 """
        user = request.user.user

        coupons = UserCoupon.objects.filter(user=user)
        result = []
        for coupon in coupons:
            result.append(coupon.Info())
        return Res.Json(Res.OK, result=result)

    @Req.getJson
    def post(self, request):
        """ 领取优惠券 """
        id = request.json_dict.get('id')

        user = request.user.user
        coupon = Coupon.objects.filter(id=id).first()
        if not coupon:
            return Res.Json(Res.ParamErr)

        UserCoupon.create(user=user, coupon=coupon)
        return Res.Json(Res.OK)